<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Shop_Model extends MY_Model {
    private $entity_name = "Shop_Entity";

    public function __construct() {
        parent::__construct();
        $this->load->model('entity/shop_entity', $this->entity_name);
    }

    public function countShop($option=array(), $all=false){
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        if(!$all){
            if(count($option)==0){
                $this->db->where('a.active_flg', STATUS_ACTIVE);
                $this->db->where('a.deleted_at', null);
                $this->db->where('c.deleted_at', null);
            } else {
                $this->db->where($option);
            }
        } else {
            if(count($option)>0){
                $this->db->where($option);
            }
        }
        return $this->db->count_all_results();
    }

    public function paging($limit, $offset, $aCol=array(), $all=false, $options = array()){
        $select = "
        a.id             AS id,
        a.title          AS title,
        a.slug           AS slug,
        a.home_page      AS home_page,
        a.payment_method AS payment_method,
        a.details        AS details,
        a.highlight_flg  AS highlight_flg,
        b.banner         AS banner,
        b.block_product_num,
        c.id             AS user_id,
        c.phone          AS phone,
        c.home_phone     AS home_phone,
        c.email          AS email,
        c.skype          AS skype,
        c.address        AS address,
        c.gmap           AS gmap,
        c.image_folder   as image_folder
        ";
        if(count($aCol) > 0){
            $select .= ','.implode(',', $aCol);
        }
        $this->db->select($select, true);
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id', 'left');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        if(!$all){
            $this->db->where('a.active_flg', STATUS_ACTIVE);
            $this->db->where('a.deleted_at', null);
            $this->db->where('b.deleted_at', null);
            $this->db->where('c.deleted_at', null);
        } else {
            $this->db->where($options);
        }
        $this->db->order_by('a.created_at', 'DESC');
        if($offset > -1){
            $this->db->limit($limit, $offset);
        }
        return $this->db->get()->result('Shop_Entity');
    }

    public function countSearchPaging($key) {
        $select = "a.id";
        $this->db->select($select, true);
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        $this->db->like('a.title', $key);
        return $this->db->count_all_results();
    }

    public function searchPaging($offset, $limit, $aCol=array(), $key){
        $select = "
        a.id             AS id,
        a.title          AS title,
        a.slug           AS slug,
        c.phone          AS phone,
        c.home_phone     AS home_phone,
        c.email          AS email,
        c.skype          AS skype,
        c.address        AS address,
        c.gmap           AS gmap,
        a.payment_method AS payment_method,
        a.details        AS details,
        c.image_folder   as image_folder,
        b.banner         AS banner,
        b.block_product_num";
        if(count($aCol) > 0){
            $select .= ','.implode(',', $aCol);
        }
        $this->db->select($select, true);
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');

        $this->db->like('a.title', $key);

        $this->db->order_by('a.created_at', 'DESC');
        if($offset > -1){
            $this->db->limit($limit, $offset);
        }
        return $this->db->get()->result('Shop_Entity');
    }

    public function getAllShop($aCol=array(), $all=false, $limit=0) {
        $select = '';
        if(count($aCol) > 0){
            $select .= ','.implode(',', $aCol);
        } else {
            $select = "
            a.id             AS id,
            a.title          AS title,
            a.slug           AS slug,
            a.payment_method AS payment_method,
            a.details        AS details,
            b.banner         AS banner,
            c.phone          AS phone,
            c.home_phone     AS home_phone,
            c.email          AS email,
            c.skype          AS skype,
            c.address        AS address,
            c.gmap           AS gmap,
            c.image_folder   AS image_folder";
        }
        $this->db->select($select, true);
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        if(!$all){
            $this->db->where('a.active_flg', STATUS_ACTIVE);
            $this->db->where('a.deleted_at', null);
            $this->db->where('b.deleted_at', null);
            $this->db->where('c.deleted_at', null);
        }
        $this->db->order_by('a.created_at', 'DESC');
        if($limit!=0){
            $this->db->limit($limit, 0);
        }
        return $this->db->get()->result('Shop_Entity');
    }

    public function getShop($id){
        $result = null;
        $this->db->select('a.id, a.user_id, a.title, a.slug, a.home_page, a.details, a.payment_method, a.created_at,
            c.phone, c.home_phone, c.email, c.skype, c.address, c.gmap', true);
        $this->db->from($this->table_shop_name. ' AS a');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        $this->db->where('a.deleted_at', NULL);
        $this->db->where('a.id', $id);
        $result = $this->db->get()->first_row('Shop_Entity');
        return $result;
    }

    public function getShopBySlug($slug, $options=array(), $getAll=false){
        $result = null;
        $select = 'a.id, a.user_id, a.title, a.slug, a.home_page, a.details, a.payment_method, a.logo,
        b.template, b.banner, b.show_page, b.block_product_num as shop_product_num,
        c.phone, c.home_phone, c.email, c.skype, c.address, c.gmap, c.image_folder';
        if(count($options)>0){
            $select .= ',' . implode(',', $options);
        }
        $this->db->select($select, true);
        $this->db->from($this->table_shop_name. ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_user_name . ' c', 'a.user_id=c.id');
        if(!$getAll){
            $this->db->where('a.deleted_at', NULL);
        }
        $this->db->where('a.slug', $slug);
        $result = $this->db->get()->first_row('Shop_Entity');
        return $result;
    }

    public function getShopByCategory($cate_id, $aCol=array(), $limit=SHOP_LIMIT, $offset=0){
        $str = "";
        if(count($aCol)>0){
            $str = implode(',', $aCol);
        } else {
            $str = "distinct(c.id), a.id, a.title, a.slug, d.image_folder,
            e.banner,
            d.phone, d.home_phone, d.address, d.email, d.skype, d.created_at, d.last_login, d.last_logout";
        }
        $this->db->select($str);
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->join($this->table_shop_category_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_category_name . ' c', 'c.id=b.cate_id');
        $this->db->join($this->table_user_name . ' d', 'a.user_id=d.id');
        $this->db->join($this->table_shop_setting_name . ' e', 'e.shop_id=a.id');
        $this->db->where('a.deleted_at', null);
        $this->db->where('b.deleted_at', null);
        $this->db->where('c.deleted_at', null);
        $this->db->where('d.deleted_at', null);
        $this->db->where('e.deleted_at', null);
        $this->db->where('b.cate_id', $cate_id);
        $this->db->limit($limit, $offset);
        $result = $this->db->get()->result('Shop_Entity');
        return $result;
    }

    public function countShopByCategory($cate_id){
        $str = "distinct(a.id) as count_row";
        $this->db->select($str);
        $this->db->from($this->table_shop_name          . ' AS a');
        $this->db->join($this->table_shop_category_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_category_name      . ' c', 'c.id=b.cate_id');
        $this->db->join($this->table_user_name          . ' d', 'a.user_id=d.id');
        $this->db->where('a.deleted_at', null);
        $this->db->where('b.deleted_at', null);
        $this->db->where('c.deleted_at', null);
        $this->db->where('d.deleted_at', null);
        $this->db->where_in('b.cate_id', $cate_id);
        return count($this->db->get()->result());
    }

    public function checkShopExist($options, $id=false){
        $this->db->from($this->table_shop_name . ' AS a');
        $this->db->where('a.id <>', $id);
        $this->db->where("(a.title ='{$options['title']}' OR a.slug='{$options['slug']}')");
        return $this->db->count_all_results();
    }

    public function update($id, $shop) {
        $this->db->trans_begin();
        $this->db->where('id', $id);
        $this->db->update($this->table_shop_name, $shop);
        //must create new highlight record
        if(isset($shop['highlight_flg'])) {
            $this->db->where('shop_id', $id);
            $this->db->update($this->table_shop_highlight_name, array('deleted_at'=>$shop['updated_at']));
            if($shop['highlight_flg']==ON){
                $this->db->insert($this->table_shop_highlight_name, array('shop_id'=>$id, 'created_at'=>$shop['updated_at']));
            }
        }
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function updateShopSetting($id, $shop_setting, $shop_slide){
        $this->db->trans_begin();
        $this->db->where('shop_id', $id);
        $this->db->update($this->table_shop_setting_name, $shop_setting);

        $this->db->where('shop_id', $id);
        $this->db->update($this->table_shop_slide_name, array('deleted_at'=>$shop_setting['updated_at']));
        foreach ($shop_slide as $key => $img) {
            $oSlide = array(
                'shop_id'    => $id,
                'image'      => $img,
                'is_avatar'  => OFF,
                'order_num'  => $key + 1,
                'created_at' => $shop_setting['updated_at']
                );
            $this->db->insert($this->table_shop_slide_name, $oSlide);
        }
        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    //////////////////////////// SHOP MANAGE AREA /////////////////////////////////
    public function getShopByUserId($userId, $selectOption=array()){
        $result = null;
        if(count($selectOption)>0){
            if(is_array($selectOption)){
                $this->db->select(implode(',', $selectOption));
            } else {
                $this->db->select($selectOption);
            }
        } else {
            $this->db->select(
                'a.id, a.user_id, c.image_folder, a.title, a.slug, a.home_page, a.details, a.payment_method, a.created_at, b.template, b.show_page, b.banner',
                true
            );
        }
        $this->db->from($this->table_shop_name. ' AS a');
        $this->db->join($this->table_shop_setting_name . ' b', 'a.id=b.shop_id');
        $this->db->join($this->table_user_name      . ' c', 'a.user_id=c.id');
        $this->db->where('a.user_id', $userId);
        $result = $this->db->get()->first_row('Shop_Entity');
        return $result;
    }

    public function getAvailableShopMenuPage(){
        $result = null;
        $this->load->model('entity/shop_page_entity', 'Shop_Page_Entity');
        $this->db->select('a.id, a.title, a.slug, a.order_num', true);
        $this->db->from($this->table_shop_page_name. ' AS a');
        $this->db->where('a.deleted_at', NULL);
        $this->db->order_by('a.order_num', 'ASC');
        $result = $this->db->get()->result('Shop_Page_Entity');
        return $result;
    }

    public function getShopPages($strPageIds){
        $result = null;
        $a = null;
        if($strPageIds!=''){
            $a = explode(',', $strPageIds);
        }
        $this->load->model('entity/shop_page_entity', 'Shop_Page_Entity');
        $this->db->select('a.id, a.title, a.slug, a.order_num', true);
        $this->db->from($this->table_shop_page_name. ' AS a');
        $this->db->where('a.deleted_at', NULL);
        if($a!=null){
            $this->db->where_in('a.id', $a);
        }
        $this->db->order_by('a.order_num', 'ASC');
        $result = $this->db->get()->result('Shop_Page_Entity');
        return $result;
    }


    public function getAllShopCategory($shop_slug, $option = array(), $aSelect=array()) {
        $this->load->model('entity/shop_category_entity', 'Shop_Category_Entity');
        $select = "a.id, a.title, a.slug, d.title as parent_title";
        if(count($aSelect)>0){
            $select = implode(',', $aSelect);
        }
        $this->db->select($select, true);
        $this->db->from($this->table_shop_category_name . ' AS a');
        $this->db->join($this->table_shop_name . ' b', 'a.shop_id=b.id');
        $this->db->join($this->table_user_name . ' c', 'b.user_id=c.id');
        $this->db->join($this->table_category_name . ' d', 'a.cate_id=d.id');
        $this->db->where('b.slug', $shop_slug);
        $this->db->where('a.deleted_at', null);
        $this->db->where('b.deleted_at', null);
        $this->db->where('c.deleted_at', null);
        $this->db->where('d.deleted_at', null);
        $this->db->order_by('a.order', 'ASC');
        $this->db->order_by('a.created_at', 'DESC');
        if (count($option) > 0) {
            $this->db->where($option);
        }
        return $this->db->get()->result('Shop_Category_Entity');
    }

    public function getBannerSlide($shop_slug){
        $this->db->select('c.image_folder, a.image, order_num', true);
        $this->db->from($this->table_shop_slide_name . ' AS a');
        $this->db->join($this->table_shop_name . ' b', 'a.shop_id=b.id');
        $this->db->join($this->table_user_name . ' c', 'b.user_id=c.id');
        $this->db->where('b.slug', $shop_slug);
        $this->db->where('a.deleted_at', null);
        $this->db->where('b.deleted_at', null);
        $this->db->where('c.deleted_at', null);
        $this->db->order_by('a.order_num');
        return $this->db->get()->result();
    }
    ///////////////////////////////////////////////////////////////////////////////

    public function checkIfRegisteringShop($id){
        $this->db->select('a.id as user_id, b.id, b.title, b.slug, b.home_page, c.template, b.details, b.payment_method');
        $this->db->from($this->table_user_name . ' AS a');
        $this->db->join($this->table_shop_name . ' b', 'b.user_id=a.id');
        $this->db->join($this->table_shop_setting_name . ' c', 'c.shop_id=b.id');
        $this->db->where('a.id', $id);
        $this->db->where('a.role', ROLE_ADVERTISER);
        $this->db->where('b.active_flg', 0);
        $result = $this->db->get()->first_row('Shop_Entity');
        return count($result) > 0 ? $result:false;
    }

    public function registerShop($objShop, $objShopSetting)
    {
        $this->db->trans_start();

        //create related shop
        $objShop['active_flg'] = STATUS_PENDING;
        $this->db->insert($this->table_shop_name, $objShop);
        $shop_id = $this->db->insert_id();

        //create related shop_setting
        $objShopSetting['shop_id'] = $shop_id;
        $this->db->insert($this->table_shop_setting_name, $objShopSetting);

        if ($this->db->trans_status() === false) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_complete();
        }
        return true;
    }

    public function acceptShopRegister($objShop){
        $this->db->trans_begin();
        $this->db->where('id', $objShop['user_id']);
        $this->db->update(
            $this->table_user_name,
            array(
                'role' => ROLE_SHOP_OWNER,
                'updated_at'=>$objShop['updated_at']
                )
            );
        $this->db->where('id', $objShop['id']);
        $this->db->update(
            $this->table_shop_name,
            array(
                'active_flg' => STATUS_ACTIVE,
                'updated_at' => $objShop['updated_at']
                )
            );
        $aShopPacket = array(
            'shop_id'=>$objShop['id'],
            'packet_id'=>3,
            'upload_time'=>0,
            'active_flg'=>1,
            'created_at'=>get_current_date()
            );
        $this->db->insert($this->table_shop_packet_name, $aShopPacket);

        if($this->db->trans_status() === false){
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }

    public function getSettingShop($id, $options){
        $this->load->model('entity/shop_setting_entity', 'Shop_Setting_Entity');
        $this->db->select(implode(',', $options));
        $this->db->from($this->table_shop_setting_name);
        $this->db->where('shop_id', $id);
        $result = $this->db->get()->first_row('Shop_Setting_Entity');
        return $result;
    }

    public function updateBlockProductNum($options){
        $this->db->trans_begin();
        $this->db->where('shop_id', $options['id']);
        $this->db->update(
            $this->table_shop_setting_name,
            array(
                'block_product_num' => $options['num'],
                'updated_at'=>$options['updated_at']
                )
            );
        if($this->db->trans_status() === false){
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
        }
        return true;
    }
}
?>